<template>
  <div class="notice-detail-container">
    <!-- 返回按钮 -->
    <div class="back-section">
      <el-button @click="$router.go(-1)" type="text" class="back-button">
        <el-icon><ArrowLeft /></el-icon>
        返回列表
      </el-button>
    </div>

    <!-- 公告详情卡片 -->
    <el-card class="detail-card" v-loading="loading">
      <!-- 类型标签右上角 -->
      <div class="type-tag-float">
        <el-tag :type="getTagType(noticeDetail.type)" size="large">
          {{ getTypeLabel(noticeDetail.type) }}
        </el-tag>
      </div>
      <!-- 标题 -->
      <h1 class="detail-title">{{ noticeDetail.title }}</h1>
      <div class="meta-row">
        <span class="meta-item">{{ formatTime(noticeDetail.publishTime) }}</span>
        <span class="meta-item">{{ noticeDetail.publisher }}</span>
        <span v-if="noticeDetail.location" class="meta-item">{{ noticeDetail.location }}</span>
      </div>
      <!-- 分隔符 -->
      <div class="meta-divider"></div>
      <!-- 活动属性 -->
      <div v-if="noticeDetail.type === 'ACTIVITY'" class="activity-attrs">
        <span v-if="noticeDetail.activityLimit" class="activity-attr">人数：{{ noticeDetail.approvedCount || 0 }}/{{ noticeDetail.activityLimit }}</span>
        <span v-if="noticeDetail.signupDeadline" class="activity-attr">截止：{{ formatTime(noticeDetail.signupDeadline) }}</span>
        <span v-if="noticeDetail.status" class="activity-attr">状态：{{ getStatusText(noticeDetail) }}</span>
      </div>
      <!-- 内容正文 -->
      <div class="content-text" v-html="formatContent(noticeDetail.content)"></div>
      <!-- 图片 -->
      <div v-if="noticeDetail.images && noticeDetail.images.trim()" class="images-section">
        <div class="image-gallery-small">
          <el-image
            v-for="(img, index) in getImageList()"
            :key="index"
            :src="resolveImageUrl(img)"
            :preview-src-list="getImageList()"
            fit="cover"
            class="gallery-image-small"
          />
        </div>
      </div>
      <!-- 附件 -->
      <div v-if="noticeDetail.attachments && noticeDetail.attachments.length > 0" class="attachments-section">
        <div class="attachment-list">
          <div v-for="attachment in noticeDetail.attachments" :key="attachment.id || attachment.name" class="attachment-item" @click="downloadAttachment(attachment)">
            <el-icon class="attachment-icon"><Document /></el-icon>
            <span class="attachment-name">{{ attachment.name || attachment.fileName }}</span>
            <span v-if="attachment.size" class="attachment-size">{{ formatFileSize(attachment.size) }}</span>
          </div>
        </div>
      </div>
      <!-- 备注 -->
      <div v-if="noticeDetail.remark" class="remark-section">
        <div class="remark-text">{{ noticeDetail.remark }}</div>
      </div>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="actions-section">
      <!-- 活动报名按钮 -->
      <el-button
        v-if="noticeDetail.type === 'ACTIVITY' && userRole !== 'ADMIN' && !isStaff"
        type="success"
        size="large"
        @click="openSignupDialog"
        :disabled="!canUserSignup(noticeDetail)"
        class="signup-button"
      >
        {{ getButtonText(noticeDetail) }}
      </el-button>

      <!-- 管理员操作 -->
      <div v-if="isAdmin && noticeDetail.publisher === currentUser" class="admin-actions">
        <el-button type="primary" @click="showSignupManagement = true" v-if="noticeDetail.type === 'ACTIVITY'">
          报名管理
        </el-button>
        <el-button type="danger" @click="deleteNotice">删除公告</el-button>
      </div>
    </div>

    <!-- 活动报名对话框 -->
    <el-dialog
      v-model="showSignupDialog"
      title="活动报名"
      width="600px"
      class="signup-dialog"
    >
      <el-form :model="signupForm" :rules="signupRules" ref="signupFormRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="signupForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="signupForm.studentId" placeholder="请输入学号"></el-input>
        </el-form-item>
        
        <el-form-item label="学院" prop="department">
          <el-input v-model="signupForm.department" placeholder="请输入学院"></el-input>
        </el-form-item>
        
        <el-form-item label="专业" prop="major">
          <el-input v-model="signupForm.major" placeholder="请输入专业"></el-input>
        </el-form-item>
        
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="signupForm.contact" placeholder="请输入联系方式"></el-input>
        </el-form-item>
        
        <el-form-item label="相关经验" prop="experience">
          <el-input
            v-model="signupForm.experience"
            type="textarea"
            :rows="4"
            placeholder="请描述您的相关经验（可选）"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSignupDialog = false">取消</el-button>
          <el-button type="primary" @click="submitSignup">提交报名</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 活动报名管理对话框 -->
    <el-dialog
      v-model="showSignupManagement"
      title="活动报名管理"
      width="1000px"
    >
      <div class="signup-management">
        <div class="management-header">
          <el-tabs v-model="signupTab" @tab-click="handleSignupTabClick">
            <el-tab-pane label="待审批" name="pending"></el-tab-pane>
            <el-tab-pane label="已通过" name="approved"></el-tab-pane>
            <el-tab-pane label="已拒绝" name="rejected"></el-tab-pane>
          </el-tabs>
        </div>
        
        <div class="signup-list">
          <el-table :data="signupList" style="width: 100%">
            <el-table-column prop="name" label="姓名" width="100"></el-table-column>
            <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
            <el-table-column prop="department" label="学院" width="150"></el-table-column>
            <el-table-column prop="major" label="专业" width="150"></el-table-column>
            <el-table-column prop="contact" label="联系方式" width="120"></el-table-column>
            <el-table-column prop="signupTime" label="报名时间" width="180">
              <template #default="scope">
                {{ formatTime(scope.row.signupTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getSignupStatusType(scope.row.status)">
                  {{ getSignupStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status === 'PENDING'"
                  type="success"
                  size="small"
                  @click="approveSignup(scope.row)"
                >
                  通过
                </el-button>
                <el-button
                  v-if="scope.row.status === 'PENDING'"
                  type="danger"
                  size="small"
                  @click="rejectSignup(scope.row)"
                >
                  拒绝
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="viewSignupDetail(scope.row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Document } from '@element-plus/icons-vue'
import { 
  getAnnouncementDetail, 
  deleteAnnouncement
} from '@/api/announcement'
import { submitActivitySignup, approveSignup as apiApproveSignup, rejectSignup as apiRejectSignup, getActivitySignups, getUserSignupDetails } from '@/api/activitySignup'
import { 
  getActivityStatusType, 
  getActivityStatusText, 
  getSignupButtonText,
  getSignupStatusType,
  getSignupStatusText,
  canSignup
} from '@/utils/activityStatus'
import resolveImageUrl from '@/utils/resolveImageUrl'

export default {
  name: 'NoticeDetail',
  components: {
    ArrowLeft,
    Document
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    
    // 响应式数据
    const loading = ref(false)
    const noticeDetail = ref({})
    const attachments = ref([])
    const isRead = ref(false)
    
    // 对话框状态
    const showSignupDialog = ref(false)
    const showSignupManagement = ref(false)
    const signupTab = ref('pending')
    const signupList = ref([])
    
    // 表单数据
    const signupForm = reactive({
      activityId: null,
      name: '',
      studentId: '',
      department: '',
      major: '',
      contact: '',
      experience: ''
    })
    const signupFormRef = ref(null)
    const signupRules = {
      name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
      studentId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
      department: [{ required: true, message: '请输入学院', trigger: 'blur' }],
      major: [{ required: true, message: '请输入专业', trigger: 'blur' }],
      contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }]
    }
    
    // 从store获取用户信息
    const currentUser = computed(() => store.state.user.userInfo.username || 'admin')
    const userRole = computed(() => store.getters['user/role'] || 'STUDENT')
    const isStaff = computed(() => userRole.value === 'STAFF')
    const userId = computed(() => {
      const id = store.state.user.userInfo.id
      if (id && id !== '') {
        const parsedId = parseInt(id)
        return isNaN(parsedId) ? 1 : parsedId
      }
      return 1
    })
    
    // 计算属性
    const isAdmin = computed(() => userRole.value === 'ADMIN')
    
    // 用户报名列表
    const mySignupList = ref([])
    
    // 监听报名管理对话框状态
    watch(showSignupManagement, (newVal) => {
      if (newVal) {
        loadSignupList()
      }
    })
    
    // 监听标签页变化
    watch(signupTab, () => {
      if (showSignupManagement.value) {
        loadSignupList()
      }
    })
    
    // 方法
    const loadNoticeDetail = async () => {
      loading.value = true
      try {
        const response = await getAnnouncementDetail(route.params.id, {
          userId: userId.value
        })
        
        if (response.code === 200) {
          noticeDetail.value = response.data
          isRead.value = response.data.isRead || false
        } else {
          ElMessage.error('获取公告详情失败')
        }
      } catch (error) {
        ElMessage.error('获取公告详情失败')
      } finally {
        loading.value = false
      }
    }
    
    const openSignupDialog = () => {
      signupForm.activityId = noticeDetail.value.id
      showSignupDialog.value = true
    }
    
    const submitSignup = async () => {
      const valid = await signupFormRef.value.validate().catch(() => false)
      if (!valid) {
        ElMessage.error('请完整填写报名信息')
        return
      }
      try {
        const response = await submitActivitySignup(signupForm)
        if (response.code === 200) {
          ElMessage.success('报名提交成功')
          showSignupDialog.value = false
          Object.assign(signupForm, {
            activityId: null,
            name: '',
            studentId: '',
            department: '',
            major: '',
            contact: '',
            experience: ''
          })
        } else {
          ElMessage.error(response.message || '报名提交失败')
        }
      } catch (error) {
        ElMessage.error('报名提交失败')
      }
    }
    
    const loadSignupList = async () => {
      try {
        const response = await getActivitySignups({
          activityId: noticeDetail.value.id,
          status: signupTab.value.toUpperCase(),
          publisher: currentUser.value
        })
        
        if (response.code === 200) {
          signupList.value = response.data
        } else {
          ElMessage.error(response.message || '获取报名列表失败')
        }
      } catch (error) {
        ElMessage.error('获取报名列表失败')
      }
    }
    
    const handleSignupTabClick = () => {
      // 标签页变化会通过watch监听器自动处理
    }
    
    const approveSignup = async (signup) => {
      try {
        const response = await apiApproveSignup({
          id: signup.id,
          status: 'APPROVED',
          publisher: currentUser.value
        })
        
        if (response.code === 200) {
          ElMessage.success('审批通过')
          loadSignupList()
          // 重新加载活动详情以更新人数显示
          loadNoticeDetail()
        } else {
          ElMessage.error(response.message || '审批失败')
        }
      } catch (error) {
        ElMessage.error('审批失败')
      }
    }
    
    const rejectSignup = async (signup) => {
      try {
        const response = await apiRejectSignup({
          id: signup.id,
          status: 'REJECTED',
          publisher: currentUser.value
        })
        
        if (response.code === 200) {
          ElMessage.success('已拒绝')
          loadSignupList()
          // 重新加载活动详情以更新人数显示
          loadNoticeDetail()
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
    
    const viewSignupDetail = (signup) => {
      const content = `
        <div style="text-align: left;">
          <p><strong>姓名：</strong>${signup.name}</p>
          <p><strong>联系方式：</strong>${signup.contact}</p>
          <p><strong>报名时间：</strong>${formatTime(signup.signupTime)}</p>
          <p><strong>状态：</strong>${getSignupStatusText(signup.status)}</p>
          ${signup.experience ? `<p><strong>相关经验：</strong>${signup.experience}</p>` : ''}
        </div>
      `
      ElMessageBox.alert(content, '报名详情', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true
      }).catch(() => {
        // 忽略取消操作，不显示错误
      })
    }
    
    const deleteNotice = async () => {
      try {
        await ElMessageBox.confirm('确定要删除这条公告吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await deleteAnnouncement(noticeDetail.value.id, {
          publisher: currentUser.value
        })
        
        if (response.code === 200) {
          ElMessage.success('删除成功')
          router.go(-1)
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 工具方法
    const getTagType = (type) => {
      const types = {
        'NEWS': 'primary',
        'NOTICE': 'warning',
        'ACTIVITY': 'success'
      }
      return types[type] || 'info'
    }
    
    const getTypeLabel = (type) => {
      const labels = {
        'NEWS': '新闻',
        'NOTICE': '通知',
        'ACTIVITY': '活动'
      }
      return labels[type] || type
    }
    
    const getStatusType = (item) => {
      return getActivityStatusType(item.status, item.signupDeadline)
    }
    
    const getStatusText = (item) => {
      return getActivityStatusText(item.status, item.signupDeadline)
    }
    
    const getButtonText = (item) => {
      return getSignupButtonText(item, mySignupList.value)
    }
    
    const canUserSignup = (item) => {
      return canSignup(item, mySignupList.value)
    }
    
    const formatTime = (time) => {
      if (!time) return ''
      return new Date(time).toLocaleString('zh-CN')
    }
    
    const formatContent = (content) => {
      if (!content) return ''
      return content.replace(/\n/g, '<br>')
    }
    
    const formatFileSize = (size) => {
      if (!size) return ''
      const units = ['B', 'KB', 'MB', 'GB', 'TB']
      let unitIndex = 0
      let formattedSize = size
      while (formattedSize >= 1024 && unitIndex < units.length - 1) {
        formattedSize /= 1024
        unitIndex++
      }
      return `${formattedSize.toFixed(2)} ${units[unitIndex]}`
    }
    
    const getImageList = () => {
      if (!noticeDetail.value.images) return []
      return noticeDetail.value.images.split(',').filter(img => img.trim())
    }
    
    const downloadAttachment = async (attachment) => {
      try {
        // 从attachment.url中提取文件名
        let fileName = attachment.url || attachment.fileUrl
        if (fileName && fileName.startsWith('/uploads/')) {
          fileName = fileName.substring(9) // 去掉'/uploads/'前缀
        }
        // 直接跳转到下载接口
        window.open(`/api/download/${fileName}`, '_blank')
      } catch (error) {
        ElMessage.error('下载失败')
      }
    }
    
    // 生命周期
    onMounted(() => {
      loadNoticeDetail()
      // 加载当前用户报名列表
      getUserSignupDetails().then(res => {
        if (res.code === 200 && Array.isArray(res.data)) {
          mySignupList.value = res.data
        }
      })
    })
    
    return {
      loading,
      noticeDetail,
      attachments,
      isRead,
      showSignupDialog,
      showSignupManagement,
      signupTab,
      signupList,
      signupForm,
      signupFormRef,
      signupRules,
      currentUser,
      userRole,
      isStaff,
      userId,
      isAdmin,
      openSignupDialog,
      loadSignupList,
      handleSignupTabClick,
      approveSignup,
      rejectSignup,
      deleteNotice,
      getTagType,
      getTypeLabel,
      getStatusType,
      getStatusText,
      getButtonText,
      canUserSignup,
      formatTime,
      formatContent,
      formatFileSize,
      getImageList,
      downloadAttachment,
      submitSignup,
      viewSignupDetail,
      getSignupStatusType,
      getSignupStatusText,
      resolveImageUrl,
      mySignupList
    }
  }
}
</script>

<style scoped>
.notice-detail-container {
  padding: 40px 0 60px 0;
  max-width: 900px;
  margin: 0 auto;
  background: #fff;
  min-height: 100vh;
}

.back-section {
  margin-bottom: 20px;
}

.back-button {
  color: #606266;
  font-size: 14px;
}

.back-button:hover {
  color: #409eff;
}

.detail-card {
  box-shadow: none;
  border: none;
  background: transparent;
  padding: 0 30px;
  position: relative;
}

.type-tag-float {
  position: absolute;
  top: 18px;
  right: 30px;
  z-index: 2;
}

.detail-title {
  margin: 0 0 10px 0;
  font-size: 32px;
  font-weight: bold;
  color: #ff6600;
  line-height: 1.3;
  letter-spacing: 1px;
  text-align: center;
}

.meta-row {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30px;
  margin-bottom: 0;
  color: #999;
  font-size: 15px;
}

.meta-item {
  color: #999;
  font-size: 15px;
}

.meta-divider {
  height: 1px;
  background: #eee;
  margin: 18px 0 18px 0;
  width: 100%;
}

.activity-attrs {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30px;
  margin-bottom: 18px;
  color: #409eff;
  font-size: 15px;
}

.activity-attr {
  font-weight: 500;
}

.content-text {
  line-height: 2;
  color: #222;
  font-size: 18px;
  margin-bottom: 30px;
  text-align: left;
  word-break: break-all;
}

.images-section {
  margin: 20px 0 0 0;
  text-align: center;
}

.image-gallery-small {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 16px;
}

.gallery-image-small {
  width: 220px;
  height: auto;
  max-width: 100%;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  border: none;
}

.attachments-section {
  margin: 30px 0 0 0;
  text-align: left;
}

.attachment-list {
  margin-top: 10px;
  padding-left: 0;
}

.attachment-item {
  background: none;
  border: none;
  box-shadow: none;
  padding: 12px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.attachment-icon {
  color: #409eff;
  font-size: 18px;
}

.attachment-name {
  color: #409eff;
  font-size: 16px;
  font-weight: 500;
  text-decoration: none;
}

.attachment-size {
  color: #999;
  font-size: 13px;
}

.remark-section {
  margin: 30px auto 0 auto;
  max-width: 760px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #ff6600;
  padding: 18px 24px;
}

.remark-text {
  margin: 0;
  color: #666;
  line-height: 1.8;
  font-size: 15px;
}

.actions-section {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 30px 0 0 0;
  background: none;
  box-shadow: none;
  border-radius: 0;
}

.signup-button {
  padding: 12px 30px;
  font-size: 16px;
  font-weight: 500;
}

.admin-actions {
  display: flex;
  gap: 15px;
}

.signup-management {
  min-height: 400px;
}

.management-header {
  margin-bottom: 20px;
}

.signup-list {
  min-height: 300px;
}

@media (max-width: 900px) {
  .notice-detail-container {
    padding: 20px 0 40px 0;
    max-width: 100vw;
  }
  .detail-card {
    padding: 0 10px;
  }
}

@media (max-width: 600px) {
  .detail-title {
    font-size: 22px;
  }
  .content-text {
    font-size: 15px;
  }
  .meta-row {
    flex-direction: column;
    gap: 8px;
    font-size: 13px;
  }
  .gallery-image-small {
    width: 100%;
    min-width: 0;
  }
}
</style> 